import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import { PageLoading } from '@ant-design/pro-layout';
import { Modal } from 'antd';
import { stringify } from 'querystring';
import React, { useState, useEffect } from 'react';
import { connect, ConnectProps, history, Redirect } from 'umi';

interface SecurityLayoutProps extends ConnectProps {
  loading?: boolean;
  currentUser?: CurrentUser;
  login?: {
    tonken?: string;
  };
}

// interface SecurityLayoutState {
//   isReady: boolean;
//   isShowReplyEdit: boolean
// }

const { confirm } = Modal;

let replyConfirmLock = 1;

const SecurityLayout: React.FC<SecurityLayoutProps> = (props) => {
  const { dispatch, children, loading, currentUser } = props;
  const [isReady, setIsReady] = useState<boolean>(false);

  useEffect(() => {
    setIsReady(true);

    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }, []);

  return (() => {
    const token = localStorage.getItem('token');
    const isLogin = token && currentUser && currentUser.pid;
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />;
    }

    if (currentUser.replyCount && replyConfirmLock) {
      replyConfirmLock = 0;
      confirm({
        title: '提示',
        content: `您还有审核不合格的问题待修改，请在我的内容页面修改`,
        okText: '马上修改',
        onOk() {
          history.push('/person/content');
        },
        onCancel() {},
      });
    }

    return children;
  })();
};

export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
}))(SecurityLayout);
